/**
 * 客户订单计划
 */
var parameter = getRequest();
var username = parameter['username'];//参数名

var m_PlanID =null; // 计划单主键
var m_orderID=null; //订单主表主键
var tabNumber;

//初始化
$(function () {
    //设置起始日期，

    initKendoUiGrid();
    initKendoUiGrid_a();
    initKendoUiGrid_b();

    btn_refresh();
    // btn_refresh_a();
    // btn_refresh_b();
    setStatus(0);

});

/**
 * 将数组去重
 * @param arr
 * @param attribute
 * @returns {[]}
 */
function unique(arr, attribute) {
    let new_arr = [];
    let json_arr = [];
    for (let i = 0; i < arr.length; i++) {
        if (new_arr.indexOf(arr[i][attribute]) == -1) {
            new_arr.push(arr[i][attribute]);
            json_arr.push(arr[i]);
        }
    }
    return json_arr;
}

// 构建表结构
function initKendoUiGrid(data) {

    var iid = new kendo.data.DataSource({data: []});
    var detail_id = new kendo.data.DataSource({data: []});
    var bill_date = new kendo.data.DataSource({data: []});
    var delivery_date = new kendo.data.DataSource({data: []});
    var bill_code = new kendo.data.DataSource({data: []});
    var order_code = new kendo.data.DataSource({data: []});
    var client_sid = new kendo.data.DataSource({data: []});
    var client_name = new kendo.data.DataSource({data: []});
    var product_sid = new kendo.data.DataSource({data: []});

    var color = new kendo.data.DataSource({data: []});
    var color_code = new kendo.data.DataSource({data: []});
    var amount = new kendo.data.DataSource({data: []});
    var price = new kendo.data.DataSource({data: []});

    var kilo = new kendo.data.DataSource({data: []});
    var remark = new kendo.data.DataSource({data: []});
    var bpQty = new kendo.data.DataSource({data: []});
    var gs = new kendo.data.DataSource({data: []});
    var cpQty = new kendo.data.DataSource({data: []});
    var fhQty = new kendo.data.DataSource({data: []});
    var kcQty = new kendo.data.DataSource({data: []});


    var dataSource = new kendo.data.DataSource({
        data: data,
        schema: {
            model: {
                fields: {
                    // amount: {type: "number"},
                    kilo: {type: "number"},
                    bpQty: {type: "number"},
                    gs: {type: "number"},
                    cpQty: {type: "number"},
                    fhQty: {type: "number"},
                    kcQty: {type: "number"},
                }
            }
        },
        aggregate: [
            // {field: "amount", aggregate: "sum"},
            {field: "kilo", aggregate: "sum"},
            {field: "bpQty", aggregate: "sum"},
            {field: "gs", aggregate: "sum"},
            {field: "cpQty", aggregate: "sum"},
            {field: "fhQty", aggregate: "sum"},
            {field: "kcQty", aggregate: "sum"},
        ],

        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;
            iid.data(unique(data, 'iid'));
            order_code.data(unique(data, 'order_code'));
            client_name.data(unique(data, 'client_name'));
            product_sid.data(unique(data, 'product_sid'));
            color.data(unique(data, 'color'));
            color_code.data(unique(data, 'color_code'));
            remark.data(unique(data, 'remark'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    var grid = $("#bill").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        persistSelection: true,
        allowCopy: true,
        title: "报表",
        columnMenu: {
            sortable: true
        },
        excel: {
            fileName: "未完工订单明细表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        columns: [
            {
                field: "", title: "序号", width: 30,
                template: "<span class='row_number'></span>", width: 40
            },
            {
                field: 'iid',
                title: '主表主键',
                hidden: true,
                width: 80,
                filterable: {multi: true, search: true, dataSource: iid},
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:center;white-space:nowrap;text-overflow:ellipsis;"},
                headerAttributes: {style: 'text-align:center;'}
            },
            {
                field: "detail_id",
                title: '明细主键',
                hidden: true,
                width: 70,
                filterable: {multi: true, search: true, dataSource: detail_id},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "bill_date",
                title: '开单日期',
                width: 130,
                footerTemplate: '总计:',
                filterable: {multi: true, search: true, dataSource: bill_date},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'bill_code',
                title: '单据编号',
                width: 150,
                filterable: {multi: true, search: true, dataSource: bill_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "order_code",
                title: '订单号',
                width: 120,
                filterable: {multi: true, search: true, dataSource: order_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'client_sid',
                title: '客户编号',
                width: 100,
                hidden: true,
                filterable: {multi: true, search: true, dataSource: client_sid},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'client_name',
                title: '客户',
                width: 130,
                filterable: {multi: true, search: true, dataSource: client_name},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'product_sid',
                title: '品名',
                width: 250,
                filterable: {multi: true, search: true, dataSource: product_sid},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'color',
                title: '颜色',
                width: 120,
                filterable: {multi: true, search: true, dataSource: color},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            // {
            //     field: 'color_code',
            //     title: '色号',
            //     width: 100,
            //     filterable: {multi: true, search: true, dataSource: color_code},
            //     attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            // {
            //     field: 'amount',
            //     title: '件数',
            //     width: 80,
            //     template: item => item['amount'] ? parseFloat(item['amount']).toFixed(0) : '',
            //     format: "{0:n1}",
            //     footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            //     footerAttributes: {style: "text-align:right;"},
            //     attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            {
                field: 'price',
                title: '单价',
                width: 100,
                filterable: {multi: true, search: true, dataSource: color_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'kilo',
                title: '订单重量',
                width: 130,
                template: item => item['kilo'] ? parseFloat(item['kilo']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            // {
            //     field: "remark",
            //     title: '备注',
            //     width: 200,
            //     filterable: {multi: true, search: true, dataSource: remark},
            //     attributes: {style: 'wtext-align:center;hite-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            {
                field: 'remark',
                title: '备注',
                width: 200,
                filterable: {multi: true, search: true, dataSource: remark},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'bpQty',
                title: '投坯',
                width: 100,
                template: item => item['bpQty'] ? parseFloat(item['bpQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'gs',
                title: '缸数',
                width: 80,
                template: item => item['gs'] ? parseFloat(item['gs']).toFixed(0) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'cpQty',
                title: '成品重',
                width: 100,
                template: item => item['cpQty'] ? parseFloat(item['cpQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'fhQty',
                title: '发货重',
                width: 100,
                template: item => item['fhQty'] ? parseFloat(item['fhQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'kcQty',
                title: '库存重',
                width: 100,
                template: item => item['kcQty'] ? parseFloat(item['kcQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

        ],
        reorderable: true,
        height: '99%',
        dataBound: function () {
            var rows = this.items();
            $(rows).each(function () {
                var index = $(this).index() + 1;
                var rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
    });
    var grid01 = $("#bill").data("kendoGrid");
    //双击事件
    grid.on('dblclick', 'tr', function () {
        //  代码
        var kGrid = $("#bill").data("kendoGrid");
        var row = kGrid.select();
        var dataItem = kGrid.dataItem(row);
        var id = dataItem['iid'];
        // window.parent.addTab('白坯计划', 'whiteplan.html?id=' + id);
        $('#A').window('open');  // open a window
        openorderbillA(id);
        setStatusA(1);
        $("#saved").hide();
        $("#audited").hide();
        $("#invalid").hide();
        // $("#saved").show();
    });
    //右击事件
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        //  代码

    });
    //  单击事件
    grid.on('click', 'tr', function () {
        //  代码
        setStatus('0-1')

    });
}

function initKendoUiGrid_a(data) {
    var iid = new kendo.data.DataSource({data: []});
    var detail_id = new kendo.data.DataSource({data: []});
    var bill_date = new kendo.data.DataSource({data: []});
    var delivery_date = new kendo.data.DataSource({data: []});
    var bill_code = new kendo.data.DataSource({data: []});
    var order_code = new kendo.data.DataSource({data: []});
    var client_sid = new kendo.data.DataSource({data: []});
    var client_name = new kendo.data.DataSource({data: []});
    var product_sid = new kendo.data.DataSource({data: []});

    var color = new kendo.data.DataSource({data: []});
    var color_code = new kendo.data.DataSource({data: []});
    var price = new kendo.data.DataSource({data: []});
    var amount = new kendo.data.DataSource({data: []});
    var kilo = new kendo.data.DataSource({data: []});
    var remark = new kendo.data.DataSource({data: []});
    var finished = new kendo.data.DataSource({data: []});

    var bpQty = new kendo.data.DataSource({data: []});
    var gs = new kendo.data.DataSource({data: []});
    var cpQty = new kendo.data.DataSource({data: []});
    var fhQty = new kendo.data.DataSource({data: []});
    var kcQty = new kendo.data.DataSource({data: []});


    var dataSource = new kendo.data.DataSource({
        data: data,
        schema: {
            model: {
                fields: {
                    // amount: {type: "number"},
                    kilo: {type: "number"},
                    bpQty: {type: "number"},
                    gs: {type: "number"},
                    cpQty: {type: "number"},
                    fhQty: {type: "number"},
                    kcQty: {type: "number"},
                }
            }
        },
        aggregate: [
            // {field: "amount", aggregate: "sum"},
            {field: "kilo", aggregate: "sum"},
            {field: "bpQty", aggregate: "sum"},
            {field: "gs", aggregate: "sum"},
            {field: "cpQty", aggregate: "sum"},
            {field: "fhQty", aggregate: "sum"},
            {field: "kcQty", aggregate: "sum"},
        ],

        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;
            iid.data(unique(data, 'iid'));
            order_code.data(unique(data, 'order_code'));
            client_name.data(unique(data, 'client_name'));
            product_sid.data(unique(data, 'product_sid'));
            color.data(unique(data, 'color'));
            color_code.data(unique(data, 'color_code'));
            remark.data(unique(data, 'remark'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    var grid = $("#bill_a").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        title: "报表",
        columnMenu: {
            sortable: true
        },
        excel: {
            fileName: "未完工订单明细表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        columns: [
            {
                field: "", title: "序号", width: 30,
                template: "<span class='row_number'></span>", width: 40
            },
            {
                field: 'iid',
                title: '主表主键',
                hidden: true,
                width: 80,
                filterable: {multi: true, search: true, dataSource: iid},
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:center;white-space:nowrap;text-overflow:ellipsis;"},
                headerAttributes: {style: 'text-align:center;'}
            },
            {
                field: "detail_id",
                title: '明细主键',
                hidden: true,
                width: 70,
                filterable: {multi: true, search: true, dataSource: detail_id},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'finished',
                title: '是否完工',
                hidden: true,
                width: 80,
                filterable: {multi: true, search: true, dataSource: finished},
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:center;white-space:nowrap;text-overflow:ellipsis;"},
                headerAttributes: {style: 'text-align:center;'}
            },
            {
                field: "bill_date",
                title: '开单日期',
                width: 130,
                footerTemplate: '总计:',
                filterable: {multi: true, search: true, dataSource: bill_date},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'bill_code',
                title: '单据编号',
                width: 150,
                filterable: {multi: true, search: true, dataSource: bill_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "order_code",
                title: '订单号',
                width: 120,
                filterable: {multi: true, search: true, dataSource: order_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'client_sid',
                title: '客户编号',
                width: 100,
                hidden: true,
                filterable: {multi: true, search: true, dataSource: client_sid},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'client_name',
                title: '客户',
                width: 130,
                filterable: {multi: true, search: true, dataSource: client_name},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: 'product_sid',
                title: '品名',
                width: 250,
                filterable: {multi: true, search: true, dataSource: product_sid},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'color',
                title: '颜色',
                width: 120,
                filterable: {multi: true, search: true, dataSource: color},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            // {
            //     field: 'color_code',
            //     title: '色号',
            //     width: 100,
            //     filterable: {multi: true, search: true, dataSource: color_code},
            //     attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            {
                field: 'price',
                title: '单价',
                width: 100,
                filterable: {multi: true, search: true, dataSource: color_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: 'kilo',
                title: '订单重量',
                width: 130,
                template: item => item['kilo'] ? parseFloat(item['kilo']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            // {
            //     field: "remark",
            //     title: '备注',
            //     width: 200,
            //     filterable: {multi: true, search: true, dataSource: remark},
            //     attributes: {style: 'wtext-align:center;hite-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            {
                field: 'remark',
                title: '备注',
                width: 200,
                filterable: {multi: true, search: true, dataSource: remark},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'bpQty',
                title: '投坯',
                width: 100,
                template: item => item['bpQty'] ? parseFloat(item['bpQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'gs',
                title: '缸数',
                width: 80,
                template: item => item['gs'] ? parseFloat(item['gs']).toFixed(0) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'cpQty',
                title: '成品重',
                width: 100,
                template: item => item['cpQty'] ? parseFloat(item['cpQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'fhQty',
                title: '发货重',
                width: 100,
                template: item => item['fhQty'] ? parseFloat(item['fhQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'kcQty',
                title: '库存重',
                width: 100,
                template: item => item['kcQty'] ? parseFloat(item['kcQty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

        ],
        reorderable: true,
        height: '99%',
        dataBound: function () {
            var rows = this.items();
            $(rows).each(function () {
                var index = $(this).index() + 1;
                var rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
            // 行样式
            let kgrid = $("#bill_a").data("kendoGrid");
            let trs = kgrid.tbody.find("tr");
            trs.each(function (i, row) {
                let data = kgrid.dataItem(row);
                let finished = data.finished;
                let printCount = data.printCount;

                // if (finished === 1) $(row).css("color", "#0f0cd0").css("text-decoration", "line-through");
                if (finished === 1) $(row).css("color", "#0f0cd0");
            });
        },
    });
    var grid01 = $("#bill_a").data("kendoGrid");
    //双击事件
    grid.on('dblclick', 'tr', function () {
        //  代码
        var kGrid = $("#bill_a").data("kendoGrid");
        var row = kGrid.select();
        var dataItem = kGrid.dataItem(row);
        var id = dataItem['iid'];
        // window.parent.addTab('白坯计划', 'whiteplan.html?id=' + id);
        $('#A').window('open');  // open a window
        openorderbillA(id);
        setStatusA(1);
        $("#saved").hide();
        $("#audited").hide();
        $("#invalid").hide();
    });
    //右击事件
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        //  代码

    });
    //  单击事件
    grid.on('click', 'tr', function () {
        //  代码
        var kGrid = $("#bill_a").data("kendoGrid");
        var row = kGrid.select();
        var dataItem = kGrid.dataItem(row);
        var finished = dataItem['finished'];
        if (finished==0){setStatus('1-1.1')}else{setStatus('1-1.2')}

    });
}

function initKendoUiGrid_b(data) {
    var iid = new kendo.data.DataSource({data: []});
    var detail_id = new kendo.data.DataSource({data: []});
    var bill_date = new kendo.data.DataSource({data: []});
    var delivery_date = new kendo.data.DataSource({data: []});
    var bill_code = new kendo.data.DataSource({data: []});
    var order_code = new kendo.data.DataSource({data: []});
    var client_sid = new kendo.data.DataSource({data: []});
    var client_name = new kendo.data.DataSource({data: []});
    var product_sid = new kendo.data.DataSource({data: []});

    var color = new kendo.data.DataSource({data: []});
    var color_code = new kendo.data.DataSource({data: []});
    var price = new kendo.data.DataSource({data: []});
    var amount = new kendo.data.DataSource({data: []});
    var kilo = new kendo.data.DataSource({data: []});
    var remark = new kendo.data.DataSource({data: []});
    var nullify_remark = new kendo.data.DataSource({data: []});


    var dataSource = new kendo.data.DataSource({
        data: data,
        schema: {
            model: {
                fields: {
                    // amount: {type: "number"},
                    kilo: {type: "number"},
                }
            }
        },
        aggregate: [
            // {field: "amount", aggregate: "sum"},
            {field: "kilo", aggregate: "sum"},
        ],

        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;
            iid.data(unique(data, 'iid'));
            order_code.data(unique(data, 'order_code'));
            client_name.data(unique(data, 'client_name'));
            product_sid.data(unique(data, 'product_sid'));
            color.data(unique(data, 'color'));
            color_code.data(unique(data, 'color_code'));
            remark.data(unique(data, 'remark'));
            nullify_remark.data(unique(data, 'nullify_remark'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    var grid = $("#bill_b").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        title: "报表",
        columnMenu: {
            sortable: true
        },
        excel: {
            fileName: "未完工订单明细表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        columns: [
            {
                field: "", title: "序号", width: 30,
                template: "<span class='row_number'></span>", width: 40
            },
            {
                field: 'iid',
                title: '主表主键',
                hidden: true,
                width: 80,
                filterable: {multi: true, search: true, dataSource: iid},
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:center;white-space:nowrap;text-overflow:ellipsis;"},
                headerAttributes: {style: 'text-align:center;'}
            },
            {
                field: "detail_id",
                title: '明细主键',
                hidden: true,
                width: 70,
                filterable: {multi: true, search: true, dataSource: detail_id},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "bill_date",
                title: '开单日期',
                width: 90,
                footerTemplate: '总计:',
                filterable: {multi: true, search: true, dataSource: bill_date},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'bill_code',
                title: '单据编号',
                width: 120,
                filterable: {multi: true, search: true, dataSource: bill_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "order_code",
                title: '订单号',
                width: 100,
                filterable: {multi: true, search: true, dataSource: order_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'client_sid',
                title: '客户编号',
                width: 100,
                hidden: true,
                filterable: {multi: true, search: true, dataSource: client_sid},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'client_name',
                title: '客户',
                width: 100,
                filterable: {multi: true, search: true, dataSource: client_name},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: 'product_sid',
                title: '品名',
                width: 200,
                filterable: {multi: true, search: true, dataSource: product_sid},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'color',
                title: '颜色',
                width: 100,
                filterable: {multi: true, search: true, dataSource: color},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            // {
            //     field: 'color_code',
            //     title: '色号',
            //     width: 80,
            //     filterable: {multi: true, search: true, dataSource: color_code},
            //     attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            {
                field: 'price',
                title: '单价',
                width: 100,
                filterable: {multi: true, search: true, dataSource: color_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'kilo',
                title: '订单重量',
                width: 100,
                template: item => item['kilo'] ? parseFloat(item['kilo']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'remark',
                title: '备注',
                width: 150,
                filterable: {multi: true, search: true, dataSource: remark},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'nullify_remark',
                title: '作废原因',
                width: 150,
                filterable: {multi: true, search: true, dataSource: nullify_remark},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "",
                title: '.',
                width: 5,
                filterable: {multi: true, search: true, dataSource: ''},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
        ],
        reorderable: true,
        height: '99%',
        dataBound: function () {
            var rows = this.items();
            $(rows).each(function () {
                var index = $(this).index() + 1;
                var rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
            // 行样式
            let kgrid = $("#bill_b").data("kendoGrid");
            let trs = kgrid.tbody.find("tr");
            trs.each(function (i, row) {
                let data = kgrid.dataItem(row);
                let state = data.status;
                let printCount = data.printCount;
                // console.log('state:'+state)
                // if (printCount > 0) $(row).css("color", "#0f0cd0");
                // if (state === 0) $(row).css("color", "red").css("text-decoration", "line-through");
                $(row).css("color", "red").css("text-decoration", "line-through");
            });
        },


    });
    var grid01 = $("#bill_b").data("kendoGrid");
    //双击事件
    grid.on('dblclick', 'tr', function () {
        //  代码
        // var kGrid = $("#bill_b").data("kendoGrid");
        // var row = kGrid.select();
        // var dataItem = kGrid.dataItem(row);
        // var id = dataItem['iid'];
        // // window.parent.addTab('白坯计划', 'whiteplan.html?id=' + id);
        // $('#A').window('open');  // open a window
        // openorderbillA(id);
        // setStatusA(1);
    });
    //右击事件
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        //  代码

    });
    //  单击事件
    grid.on('click', 'tr', function () {
        //  代码
        setStatus('0-1')

    });
}

//新增
function addplan(data) {
    switch (data) {
        case '新增订单' :
            $('#A').window('open');  // open a window
            m_orderID =null;
            setStatusA(0);
            updateorderbillA();
            ClearallorderBill();

            break;

        case '生成计划单' :
            var kGrid;
            if (tabNumber==0){
                kGrid = $("#bill").data("kendoGrid");
            }else if (tabNumber==1){
                kGrid = $("#bill_a").data("kendoGrid");
            }
            var row = kGrid.select();
            var dataItem = kGrid.dataItem(row);
            var m_orderDetailID = dataItem['detail_id'];
            console.log('明细表主键：')
            console.log(m_orderDetailID)
            if (m_orderDetailID>0){
                $('#B').window('open');
                addplanB(m_orderDetailID);
            }else{
                $.messager.alert('提示','请选择有效单据！')
            }

            break;
    }

}

//刷新
function refresh() {
    setStatus(tabNumber)
    switch (tabNumber) {
        case 0:
            btn_refresh();

            break;
        case 1:
            btn_refresh_a();
            break;
        case 2:
            btn_refresh_b();
            break;
    }
}

function btn_refresh() {
    var kGrid = $("#bill").data("kendoGrid");

    var data1 = $('#start').datebox('getValue');
    var data2 = $('#end').datebox('getValue');
    $.ajax({
        url: strLin + 'dynamicQuery/callProc',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(['usp_getOrderdetailUnfinished',data1,data2]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
                kGrid.dataSource.data(data);
        }
    });
}

function btn_refresh_a() {
    var kGrid = $("#bill_a").data("kendoGrid");

    var data1 = $('#start').datebox('getValue');
    var data2 = $('#end').datebox('getValue');
    $.ajax({
        url: strLin + 'dynamicQuery/callProc',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(['usp_getOrderdetailall',data1,data2]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            kGrid.dataSource.data(data);
        }
    });
}

function btn_refresh_b() {
    var kGrid = $("#bill_b").data("kendoGrid");

    var data1 = $('#start').datebox('getValue');
    var data2 = $('#end').datebox('getValue');
    $.ajax({
        url: strLin + 'dynamicQuery/callProc',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(['usp_getOrderdetailtoVoid',data1,data2]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            kGrid.dataSource.data(data);
        }
    });
}

//打印
function btn_print() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    let filtrer = kGrid.dataSource.filter();
    let allData = kGrid.dataSource.data();
    let query = new kendo.data.Query(allData);
    let data = query.filter(filtrer).data;
    if (data != undefined && data.length > 0) {
        let arr = [];
        for (let i = 0; i < data.length; i++) {
            let item = data[i]['planId'];
            if (item) arr.push(item);
        }
        if (arr.length <= 0) return;
        let reportlets = [];
        let printTemplate = {};
        printTemplate.ids = arr.join(',');
        printTemplate.reportlet = PRINT_TEMPLATE_NAME;
        reportlets.push(printTemplate);
        if (reportlets.length <= 0) {
            $.messager.show({title: '提示', msg: '没有明细！无法打印！'});
            return;
        }
        let config = {
            url: "ReportServer",
            isPopUp: false,
            data: {
                reportlets: reportlets
            }
        };
        FR.doURLPDFPrint(config);
    }
}

//导出
function btn_export() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    kGrid.saveAsExcel();
}

//重置
function btn_reset() {
    $.messager.show('提示', '该页面暂无chongzh业务！');
}

//  清除
function btn_cancel_filter() {
    switch (tabNumber) {
        case 0:
            let kGrid0 = $("#bill").data("kendoGrid");
            if (kGrid0 != undefined) {
                kGrid0.dataSource.filter({});
            }
            break;
        case 1:
            let kGrid1 = $("#bill_a").data("kendoGrid");
            if (kGrid1 != undefined) {
                kGrid1.dataSource.filter({});
            }
            break;
        case 2:
            let kGrid2 = $("#bill_b").data("kendoGrid");
            if (kGrid2 != undefined) {
                kGrid2.dataSource.filter({});
            }
            break;
    }
}

//右键菜单弹出框
function menuHandler() {

}

function getDate(param) {
    if (isNaN(param)) {
        param = 0;
    }
    var curDate = new Date();
    var newDate = new Date(curDate);
    newDate.setDate(curDate.getDate() + param);
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1;
    var date = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
    var separator = '-';
    return year + separator + month + separator + date;
}

//关闭当前标签页事件
function closeTab() {
    window.parent.closeTab();
}

//获取报表对应的起始日期
function getreportStartDate() {
    $.ajax({
        url: strLin + '/configAll/all',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let  data=cdata.data;
            console.log(data);
            data1=data.filter(item=>item.config_name==="计划序时表_pc");
            var starDate=getDay(-data1[0].value_num);
            console.log(starDate);
            $("#start").datebox("setValue", starDate);

            // initKendoUiGrid();
            btn_refresh();

        }
    })
}

//颜色格式化
function styler(v, r, i) {
    return v ? "background-color:" + v + ";color:" + v + ";" : "";
}


function onSelect(title, index) {
    tabNumber=index;
    setStatus(index);
    switch (index) {
        case 0:
            $("#start").textbox({disabled: true});
            $("#end").textbox({disabled: true});
            // if ($('#bill').data('kendoGrid') == undefined) {
            //     btn_refresh();
            // }
            btn_refresh();
            break;
        case 1:
            $("#start").textbox({disabled: false});
            $("#end").textbox({disabled: false});
            // if ($('#bill_a').data('kendoGrid')._data.length ==0) {
            //     btn_refresh_a();
            // }
            btn_refresh_a();
            break;
        case 2:
            $("#start").textbox({disabled: false});
            $("#end").textbox({disabled: false});
            // if ($('#bill_b').data('kendoGrid')._data.length ==0) {
            //     btn_refresh_b();
            // }
            btn_refresh_b();
            break;
    }
}

function setStatus(index) {
    let msg = {
        'tab0': ['生成计划单','设置完工','取消完工'],
        'tab1': ['生成计划单','设置完工','取消完工'],
        'tab2': ['生成计划单','设置完工','取消完工'],

        'tab0-1': ['取消完工'],
        'tab1-1': [''],
        'tab1-1.1': ['取消完工'],
        'tab1-1.2': ['设置完工'],
        'tab2-1': ['生成计划单'],
    };
    setTimeout(function () {
        $('#north').find('a[class*="easyui-linkbutton"]').each(function (item, i) {
            let text = $(i).linkbutton('options').text;
            if (msg[`tab${index}`] == undefined) return false;
            if (msg[`tab${index}`].indexOf(text) > -1) {
                $(i).linkbutton('disable');
            } else {
                $(i).linkbutton('enable');
            }
        })
    }, 0);
    // if (index >= 3) {
    //     $('#state').switchbutton('enable');
    // } else {
    //     $('#state').switchbutton('disable');
    // }
}

function setStatusA(index) {
    let msg = {
        'tab0-1': ['新增出库', '领料退回', '盘点'],
        'tab1-1': ['原料退回', '领料退回'],
        'tab2-1': ['新增入库', '原料退回', '新增出库', '盘点'],
        'tab0': ['新增', '修改', '复制','作废'],
        'tab1': ['保存','新增行','复制行','删除行','刷新'],
        'tab2': ['新增入库', '原料退回', '新增出库', '领料退回', '盘点'],
    };
    setTimeout(function () {
        $('#topA').find('a[class*="easyui-linkbutton"]').each(function (item, i) {
            let text = $(i).linkbutton('options').text;
            if (msg[`tab${index}`] == undefined) return false;
            if (msg[`tab${index}`].indexOf(text) > -1) {
                $(i).linkbutton('disable');
            } else {
                $(i).linkbutton('enable');
            }
        })
    }, 0);
    // if (index >= 3) {
    //     $('#state').switchbutton('enable');
    // } else {
    //     $('#state').switchbutton('disable');
    // }
}

//设置完工
function setfinish() {
    var kGrid = $("#bill").data("kendoGrid");
    var row = kGrid.select();
    var dataItem = kGrid.dataItem(row);
    var id = dataItem['iid'];
    var detail_id = dataItem['detail_id'];

    let SQL={"main":{"iid":id,'state':1},"details":[{"iid":detail_id,"finished":1}]};
    console.log(SQL)
    $.ajax({
        url: strLin + 'billOrder/update',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(SQL),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            refresh();
        }
    });

}
//取消完工
function cancelfinish() {
    var kGrid = $("#bill_a").data("kendoGrid");
    var row = kGrid.select();
    var dataItem = kGrid.dataItem(row);
    var id = dataItem['iid'];
    var detail_id = dataItem['detail_id'];

    let SQL={"main":{"iid":id,'state':1},"details":[{"iid":detail_id,"finished":0}]};
    console.log(SQL)
    $.ajax({
        url: strLin + 'billOrder/update',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(SQL),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            refresh();
        }
    });
}

